package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.cucc.common.util.DateUtils;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.*;
import com.iwhalecloud.bss.kite.service.attr.AttrData;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.base.util.LocalAttrUtils;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.zsmart.core.util.DateUtil;
import org.apache.commons.collections.MapUtils;
import org.joda.time.LocalDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Map;

/**
 * @Classname RequiredDateAttrHandler
 * @Description 时间类型字段，默认当前时间+n天
 * @Author zhang.song
 * @Date 2021-02-23 10:01
 */
@Service
public class RequiredDateJPWAttrHandler extends AbstractAttrHandler {


    @Autowired
    private IQuerySceneInstService querySceneInstService;
    @Override
    public void init(CommonAttrVO commonAttr){
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);

        String nodeCode = querySceneInstService.getExtParameterValue(sceneInstId, "nodeCode");
        String custId = KiteWebContext.getContext().getCust().getCustId();
        KiteAttr attr =querySceneInstService.getCommonAttr(sceneInstId, commonAttr.getFieldName());
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        KiteProdInst prodInst = querySceneInstService.listProdInstsFromOfferInst(KiteWebContext.getContext().getCustId(), kiteSceneInst.getRootInstId()).stream()
            .filter(inst -> !KiteStringUtils.equalsAny(inst.getActionType().name(), ActionType.X.name(), ActionType.D.name()))
            .findFirst().orElse(null);
        // 核查
        String value = commonAttr.getValue();
        if(KiteStringUtils.isEmpty(commonAttr.getDefaultValue())){
            String productId = prodInst.getSpecId();
            if(KiteStringUtils.equals(kiteSceneInst.getServiceOfferId(),LocalServiceOfferConsts.SERVICE_OFFER_RESOURCE_CHECK)){
                //核查重提

                if("OrderResubmit".equals(nodeCode)){
                    value = LocalAttrUtils.compareDate(commonAttr, prodInst.getSpecId(),null);
                    commonAttr.setDefaultValue(value);
                }else{
                    value = LocalAttrUtils.getInstance().AZOffsetDay(productId ,null,null);
                    commonAttr.setDefaultValue(value);
                }
                commonAttr.setValue(value);
            }else{
                nonCrossDomain(commonAttr,attr,productId);
            }

            //        核查追单追单校验
            String BIZ_TYPE = MapUtils.getString(this.querySceneInstService.getExtParameter(sceneInstId),"serviceOfferId");
            if (KiteStringUtils.equals(LocalServiceOfferConsts.SERVICE_OFFER_FOLLOW, BIZ_TYPE)&&"OrderResourceCheck".equals(nodeCode)) {
                commonAttr.setValue(LocalAttrUtils.compareDate(commonAttr, prodInst.getSpecId(),null));
                commonAttr.setDefaultValue(LocalAttrUtils.compareDate(commonAttr, prodInst.getSpecId(),null));
            }
        }
        // 订单补录情况，来单属性为空时，不设置默认值，否则会有展示属性值与甩单填写不一致情况
        if(KiteStringUtils.isEmpty(value)&&!KiteStringUtils.isEmpty(commonAttr.getDefaultValue())){
            commonAttr.setValue(commonAttr.getDefaultValue());
            commonAttr.setValueDesc(commonAttr.getDefaultValue());
        }
        setCommonAttr(commonAttr);

    }
    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        KiteAttr kiteAttr =querySceneInstService.getCommonAttr(sceneInstId,fieldName);
        String serviceOfferId = querySceneInstService.getSceneInst(sceneInstId).getServiceOfferId();
        if(KiteStringUtils.equals(serviceOfferId,LocalServiceOfferConsts.SERVICE_OFFER_RESOURCE_CHECK)){
            //核查重提
            if(kiteAttr!=null&&KiteStringUtils.isNotEmpty(kiteAttr.getDefaultValue())&& DateFormatUtils.compareDate(value,kiteAttr.getDefaultValue() , DateFormatUtils.DATE_MINUTE_FORMAT) < 0){
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("可选择的日期不能早于初始化的日期:"+kiteAttr.getDefaultValue());
            }
        }
        //        核查追单追单校验

        if (KiteStringUtils.equals(serviceOfferId,LocalServiceOfferConsts.SERVICE_OFFER_FOLLOW)) {
            Map<String, Object> extParams = ContextUtil.getLoginInfo().getUserInfo().getExtParams();
            if("OrderResourceCheck".equals(extParams.get("nodeCode"))){
                if(kiteAttr!=null&&KiteStringUtils.isNotEmpty(kiteAttr.getDefaultValue())&&DateFormatUtils.compareDate(value,kiteAttr.getDefaultValue() , DateFormatUtils.DATE_MINUTE_FORMAT) < 0){
                    ErrorConsts.BUSI_COMMON_ERROR.throwOut("可选择的日期不能早于初始化的日期:"+kiteAttr.getDefaultValue());
                }
            }
        }
        if (KiteStringUtils.isEmpty(value)){
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        // 是否为页面初始化渲染，是（T），跳过校验
        String isInitPageRenderFlag = querySceneInstService.getExtParameterValue(sceneInstId, "isInitPageRenderFlag");
        if (KeyConsts.IFTRUE_T.equals(isInitPageRenderFlag)) {
            return super.apply(sceneInstId, fieldName, value, valueDesc);
        }
        String completeTimePattern = LocalAttrUtils.FormatByValue(value);

        Date complateDate = null;
        try{
            complateDate = DateUtils.parseStrToDate(value, completeTimePattern);
        }catch (Exception e){
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("日期转换异常");
        }
        //全程要求完成时间
        Date allCompleteDate = null;
        String allCompleteTimeStr = querySceneInstService.getCommonAttrValue(sceneInstId, "ORD10012");
        if(KiteStringUtils.isNotEmpty(allCompleteTimeStr)){
            try{
                allCompleteDate = DateUtils.parseStrToDate(allCompleteTimeStr, completeTimePattern);
            }catch(Exception e){
                ErrorConsts.BUSI_COMMON_ERROR.throwOut("日期转换异常");
            }

            //A、Z端要求完成时间 不能晚于全程要求完成时间
            if (null != complateDate && DateUtil.compare(complateDate,allCompleteDate) >1){
                BssException.throwOut(KeyConsts.LOG_MODULE, "", "A、Z端要求完成时间不能晚于全程要求完成时间");
            }
        }
        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }
    /**
     * 不同产品默认 当日往后加天数getAddDays
     */
    private static int getAddDays(String productId) {
        int result = 3;
        switch (productId) {
            case "10003665":
                result = 5;
                break;
            default:
                break;
        }
        return result;
    }
    private void nonCrossDomain(CommonAttrVO commonAttr,KiteAttr attr,String productId){

        LocalDateTime nowDate = LocalDateTime.now();
        // 追加天数
        String value = nowDate.plusDays(getAddDays(productId)).format(DateTimeFormatter.ofPattern(DateFormatUtils.DATE_MINUTE_FORMAT));
        attr.setValue(value);
        attr.setValueDesc(value);
        attr.setDefaultValue(value);
        commonAttr.setValue(value);
        commonAttr.setValueDesc(value);
        commonAttr.setDefaultValue(value);
    }
}
